package com.xuzhiguang.light.gateway.server.http.netty;

import com.xuzhiguang.light.gateway.common.handler.GatewayRequestHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xuzhiguang
 */
@Slf4j
public class NettyHttpServerHandler extends ChannelInboundHandlerAdapter {

    private final GatewayRequestHandler handler;

    public NettyHttpServerHandler(GatewayRequestHandler handler) {
        this.handler = handler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            handler.handle(new NettyHttpRequest(request, System.currentTimeMillis()), new NettyHttpRequestContext(ctx));
        } else {
        log.error("[NettyHttpServerHandler] message type is not httpRequest: {}", msg);
        boolean release = ReferenceCountUtil.release(msg);
        if(!release) {
            log.error("[NettyHttpServerHandler] release fail 资源释放失败");
        }
    }


    }

}
